package com.ctshk.rpc.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.MainDataStationDTO;
import com.ctshk.rpc.system.entity.MainDataStation;
import com.ctshk.rpc.system.enums.ISCode;
import com.ctshk.rpc.system.mapper.MainDataStationMapper;
import com.ctshk.rpc.system.req.MainDataStationListReq;
import com.ctshk.rpc.system.req.MainDataStationReq;
import com.ctshk.rpc.system.req.main.data.StationUpdateStatusReq;
import com.ctshk.rpc.system.service.IMainDataStationService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 火车站点主数据 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-04-23
 */
@DubboService
public class MainDataStationServiceImpl extends ServiceImpl<MainDataStationMapper, MainDataStation> implements IMainDataStationService {

    @Autowired
    private MainDataStationMapper stationMapper;

    @Override
    public Result<PageResponse<MainDataStationDTO>> list(MainDataStationListReq req) {
        QueryWrapper<MainDataStation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MainDataStation::getIsDeleted, IsDeletedCode.NO.getCode());
        wrapper.lambda().like(StringUtils.isNotBlank(req.getName()),MainDataStation::getStationName,req.getName());
        if (null != req.getStatus()) {
            wrapper.lambda().eq(MainDataStation::getStatus, req.getStatus());
        }
        IPage<MainDataStation> pageParam = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<MainDataStation> pageResult = stationMapper.selectPage(pageParam, wrapper);
        List<MainDataStation> records = pageResult.getRecords();
        List<MainDataStationDTO> dtoList = EntityUtil.copyList(records, MainDataStationDTO.class);
        PageResponse<MainDataStationDTO> pageResponse = new PageResponse<>(dtoList,
                pageResult.getCurrent() == 1,
                pageResult.getTotal() <= (pageResult.getCurrent() * pageResult.getSize()),
                pageResult.getTotal(), pageResult.getCurrent(),
                pageResult.getSize());
        return Result.success(pageResponse);
    }

    @Override
    public Result detail(Long id) {
        QueryWrapper<MainDataStation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MainDataStation::getId, id);
        wrapper.lambda().eq(MainDataStation::getIsDeleted, IsDeletedCode.NO.getCode());
        wrapper.lambda().eq(MainDataStation::getStatus, ISCode.NO.getCode());
        MainDataStation mainDataStation = stationMapper.selectOne(wrapper);
        MainDataStationDTO dto = EntityUtil.copy(mainDataStation, MainDataStationDTO.class);
        return Result.success(dto);
    }

    @Override
    public Result add(MainDataStationReq req, TokenUser tokenUser) {
        LocalDateTime now = LocalDateTime.now();
        MainDataStation mainDataStation = EntityUtil.copy(req, MainDataStation.class);
        mainDataStation.setId(IdWorker.getId());
        mainDataStation.setCreateId(tokenUser.getId());
        mainDataStation.setModifiedId(tokenUser.getId());
        mainDataStation.setModifiedName(tokenUser.getUsername());
        mainDataStation.setGmtCreate(now);
        mainDataStation.setGmtModified(now);
        mainDataStation.setIsDeleted(IsDeletedCode.NO.getCode());
        stationMapper.insert(mainDataStation);
        return Result.success();
    }

    @Override
    public Result batchAdd(List<MainDataStationReq> req) {
        LocalDateTime now = LocalDateTime.now();
        List<MainDataStation> mainDataStationList = EntityUtil.copyList(req, MainDataStation.class);
        for (MainDataStation mainDataStation : mainDataStationList) {
            mainDataStation.setId(IdWorker.getId());
            mainDataStation.setGmtCreate(now);
            mainDataStation.setGmtModified(now);
            mainDataStation.setIsDeleted(IsDeletedCode.NO.getCode());
        }
        // 删除旧的站点数据
        List<String> stationEnList = mainDataStationList.stream().map(MainDataStation::getStationName).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(stationEnList)) {
            stationMapper.delete(new QueryWrapper<MainDataStation>().lambda().in(MainDataStation::getStationName, stationEnList));
        }
        stationMapper.insertBatchSomeColumn(mainDataStationList);
        return Result.success();
    }

    @Override
    public Result update(MainDataStationReq req, TokenUser tokenUser) {
        LocalDateTime now = LocalDateTime.now();
        MainDataStation mainDataStation = EntityUtil.copy(req, MainDataStation.class);
        mainDataStation.setModifiedId(tokenUser.getId());
        mainDataStation.setModifiedName(tokenUser.getUsername());
        mainDataStation.setGmtModified(now);
        baseMapper.updateById(mainDataStation);
        return Result.success();
    }

    @Override
    public Result modifyStatus(StationUpdateStatusReq stationUpdateStatusReq, TokenUser currentUser) {
        QueryWrapper<MainDataStation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", stationUpdateStatusReq.getId());
        MainDataStation mainDataStation = baseMapper.selectOne(queryWrapper);
        if (mainDataStation != null) {
            mainDataStation.setStatus(stationUpdateStatusReq.getStatus());
            baseMapper.updateById(mainDataStation);
            return Result.success(mainDataStation.getId());
        }
        if (mainDataStation == null) {
            throw new BusinessException(SystemError.MAINDATA_4021);
        }
        return Result.success();
    }

    /**
     * 获取所有站点信息
     * @return
     */
    @Override
    public List<MainDataStationDTO> listAll() {
        QueryWrapper<MainDataStation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MainDataStation::getIsDeleted, IsDeletedCode.NO.getCode());
        wrapper.lambda().eq(MainDataStation::getStatus, ISCode.NO.getCode());
        return EntityUtil.copyList(stationMapper.selectList(wrapper), MainDataStationDTO.class) ;
    }
}
